package com.qili.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.qili.base.entity.CurrentUser;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.sys.SysRoleUser;
import com.qili.entity.sys.SysUser;
import com.qili.mapper.sys.SysRoleUserMapper;
import com.qili.service.SysUserService;
import com.qili.service.it.ItIndexService;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.sys.RoleService;
import com.qili.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuyang
 * @date 2021/3/8
 * @description
 */
@RequestMapping("/it")
@Controller
@Slf4j
public class ItIndexController {

    @Autowired
    ItIndexService itIndexService;
    @Autowired
    SysUserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SupervisorFileService supervisorFileService;

    public List<SysRoleUser> selectByCondition(SysRoleUser sysRoleUser) {
        return sysRoleUserMapper.selectByCondition(sysRoleUser);
    }

    /**
     * IT知识库首页
     * @param model
     * @return
     */
    @RequestMapping("index")
    @RequiresPermissions("it:index")
    public String showIndex(Model model, HttpServletRequest request){
        //查询IT知识库文件夹
        List<SupervisorFile> fileList = itIndexService.selectThreeLevelFiles();
        model.addAttribute("first",fileList);

        //带出用户头像姓名
        CurrentUser currentUser = CommonUtil.getUser();
        String userId=CommonUtil.getUserId();
        SysUser sysUser=sysUserService.selectByPrimaryKey(userId);
        if(sysUser==null){
            // 跳转到登陆页面
            request.setAttribute("type","login");
            return "/login";
        }
        // 个人中心设置的数量
        String tagnum=sysUser.getNumTag();
        currentUser.setNumTag(tagnum);
        String AsTags = currentUser.getTags();
        String[] AyTags;
        if (StringUtil.isNotBlank(AsTags)  &&  StringUtil.isNotBlank(tagnum) ) {
            String[] newAyTags=new String[Integer.valueOf(tagnum)];
            AyTags = AsTags.split(";");
            int  length=AyTags.length;
            if(Integer.valueOf(tagnum)<length){
                //清除多余的0
                for (int i = 0; i < length; i++) {
                    if(i<Integer.valueOf(tagnum)){
                        newAyTags[i]=AyTags[i];
                    }
                }
                currentUser.setTags( StringUtils.join(newAyTags, ";") + ";");
            }
        }
        Session session = com.qili.core.shiro.Principal.getSession();
        session.setAttribute("currentPrincipal", currentUser);
        SupervisorFile supervisorFile =  supervisorFileService.getPersonalImg(userId);
        request.setAttribute("file", supervisorFile);
        return "itIndex";
    }

    /*
     * @param superiorId        父级文件夹id
     * @Desc                    根据父级id(superior_id字段)查询其下的   "我"拥有查看权限的文件夹  只查询文件夹
     * @return
     */
    @RequestMapping("/selectDic")
    @ResponseBody
    public ArrayList<SupervisorFile> selectItDic(String superiorId, String fileType){
        //判断用户是否拥有查看所有IT文件夹的角色
        boolean seeAll = itIndexService.canISeeAll();

        Map map=new HashMap();
        map.put("superiorId",superiorId);
        map.put("fileType",fileType);
        if(!seeAll){
            map.put("examine",CommonUtil.getUserRoleList());
        }
        List<SupervisorFile> list= itIndexService.selectItknowledge(map);
        return (ArrayList)list;
    }

    /**
     * @param superiorId        父级文件夹id
     * @param limit
     * @Desc                    根据父级id(superior_id字段)查询其下的   "我"拥有查看权限的文件  只查询文件
     * @return
     */
    @RequestMapping("selectItFile")
    @ResponseBody
    public ArrayList<SupervisorFile> selectItFile(String superiorId,Integer limit,String hotTest,String userId){
        Map map=new HashMap();
        map.put("superiorId",superiorId);
        map.put("limit",limit);
        map.put("hotTest",hotTest);
        map.put("userId",userId);
        //文件的查看权限
        map.put("examine",CommonUtil.getUserRoleList());
        List<SupervisorFile> list= itIndexService.selectItFile(map);
        return (ArrayList)list;
    }

    /**
     *首页最新最热门收藏夹文件展示
     * @param model
     * @return
     */
    @RequestMapping("homePage")
    public String homePage(Model model){
        //IT知识库最新文件查询
        List<SupervisorFile> newfile = selectItFile(null,10,null,null);
        model.addAttribute("newfile",newfile);
        //IT知识库最热门文件查询
        List<SupervisorFile> hotFile =selectItFile(null,10,"hotTest",null);
        model.addAttribute("hotFile",hotFile);
        //根据当前登录人查询IT知识库收藏文件
        Subject sub = SecurityUtils.getSubject();
        CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
        String userid = currentUser.getId();
        List<SupervisorFile> collectFile =selectItFile(null,null,null,userid);
        model.addAttribute("collectFile",collectFile);
        //判断用户是否有权限查看详情
        Boolean hasSeeDetailPermission = userService.isHasPermission("it:details");
        model.addAttribute("details",hasSeeDetailPermission?"1":"0");;
        return "fileShow";
    }


    /**
     * 遍历supervisor_file表所有的文件:
     * 1.只处理url不为空的
     *
     *      格式化url字段
     *      根据url查找系统文件
     *
     *    2.只处理系统中真实存在的,如果不存在,暂时不处理
     *
     *
     */
    @PostMapping("/formatSupervisorFile")
    @ResponseBody
    public void formatSupervisorFile(){
        List<SupervisorFile> fileList = supervisorFileService.selectAll();
        //遍历supervisor_file表中的数据
        for(SupervisorFile dbFile : fileList){
            String url = dbFile.getUrl();
            if(StringUtils.isNotBlank(url)){
                File file = new File(url);
                dbFile.setUrl(file.getPath());
                SupervisorFile updateFile = new SupervisorFile();
                updateFile.setId(dbFile.getId());
                updateFile.setUrl(dbFile.getUrl());
                supervisorFileService.updateByPrimaryKeySelective(updateFile);
                if(file.exists() && file.isFile()){
                    supervisorFileService.setFilePathDics(dbFile);
                }else{
                    log.warn("文件id("+dbFile.getId()+"),url("+dbFile.getUrl()+")对应的真实文件不存在");
                }
            }
        }
    }

    /**
     * 格式化supervisor_file表的url
     */
    @GetMapping("/formatSupervisorFileUrl")
    @ResponseBody
    public void formatSupervisorFileUrl(){
        List<SupervisorFile> fileList = supervisorFileService.selectAll();
        //遍历supervisor_file表中的数据
        for(SupervisorFile dbFile : fileList){
            String url = dbFile.getUrl();
            if(StringUtils.isNotBlank(url)){
                File file = new File(url);
                SupervisorFile updateFile = new SupervisorFile();
                updateFile.setId(dbFile.getId());
                updateFile.setUrl(file.getPath());
                supervisorFileService.updateByPrimaryKeySelective(updateFile);
                if(!file.exists()){
                    log.warn("文件id("+dbFile.getId()+"),url("+dbFile.getUrl()+")对应的真实文件不存在");
                }
            }
        }
    }

    /**
     * 格式化sys_user表的dicInfo
     */
    @GetMapping("/formatSysUserInfoDic")
    @ResponseBody
    public void formatSysUserInfoDic(){
        List<SysUser> userList = userService.selectAll();
        for(SysUser user : userList){
            String url = user.getInfoDic();
            if(StringUtils.isNotBlank(url)){
                File file = new File(url);
                    SysUser updateUser = new SysUser();
                    updateUser.setId(user.getId());
                    updateUser.setInfoDic(file.getPath());
                    userService.updateByPrimaryKeySelective(updateUser);
            }
        }
    }


    @GetMapping("/formatSupervisorFileAboutProject")
    @ResponseBody
    public void formatSupervisorFileAboutProject(){
        List<SupervisorFile> projectFileList = supervisorFileService.selectAllProjectFile();
        List<BaseDict> projectFileDictList = DictUtil.getDictByType(DictTypes.XMWJ);
        List<String> projectFileIds = projectFileDictList.stream().map(BaseDict::getBadtCode).collect(Collectors.toList());
        //遍历supervisor_file表中的数据
        if(CollectionUtil.isNotEmpty(projectFileList)){
            for(SupervisorFile dbFile : projectFileList){
                //获取它的父文件夹,如果父文件夹不是项目指定文件夹,那么就是项目创建的文件夹,设置这个文件夹的project_id字段
                setProjectFileParent(dbFile,projectFileIds);
            }
        }
    }

    private void setProjectFileParent(SupervisorFile file,List<String> projectFileIds){
        log.info("----------------设置一个项目文件/文件夹----------------");
        log.info(file.getFileName());
        log.info("项目id:"+file.getProjectId());
        if(StringUtils.isNotBlank(file.getSuperiorId())){
            if(!projectFileIds.contains(file.getSuperiorId())){
                log.info("其父文件夹,不是指定的项目文件夹");
                SupervisorFile parentUpdateFile = new SupervisorFile();
                parentUpdateFile.setId(file.getSuperiorId());
                parentUpdateFile.setProjectId(file.getProjectId());
                supervisorFileService.updateByPrimaryKeySelective(parentUpdateFile);
                setProjectFileParent(parentUpdateFile,projectFileIds);
            }
        }
    }

}
